//
//  InformationViewController.m
//  Marketing
//
//  Created by HanenDev on 16/2/25.
//  Copyright © 2016年 Hanen 3G 01. All rights reserved.
//

#import "InformationViewController.h"
#import "QRCodeGenerator.h"

#define ROWH 50.0f

@interface InformationViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
{
    NSArray     *_titleArray;
    NSArray     *_dataArray;
    UILabel     *qrNameLabel;
    UITableView *_tableView;
    UIButton    *QRbutton;
    UIButton    *btnSave;
}
@property(nonatomic,strong)UIView         *qrView;
@property(nonatomic,strong)UIImageView    *qrImageView;
@property(nonatomic,strong)UIImageView    *bgImage;

@property(nonatomic,strong)UILabel        *nameLab;
@property(nonatomic,strong)UILabel        *telLab;
@property(nonatomic,strong)UITextField    *departTF;
@property(nonatomic,strong)UITextField    *positionTF;
@property(nonatomic,strong)UIButton    *headerImg;

@end

@implementation InformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = graySectionColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = NO;
    
    
    self.navigationItem.titleView = [ViewTool getNavigitionTitleLabel: @"个人信息"];
    if ([_type intValue] == 1) {//
//        _titleArray = @[@"头像",@"姓名",@"电话",@"二维码",@"公司名称",@"职位"];
    }else{//管理员 可以修改部门和职位
        
    }
    
    _titleArray = @[@"头像",@"姓名",@"电话",@"二维码",@"所属部门",@"职位"];
    [self createUI];
    
    [self createQRView];
}

- (void)createUI{
    self.navigationItem.leftBarButtonItem=[ViewTool getBarButtonItemWithTarget:self WithAction:@selector(goToBack)];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20 - 1, KSCreenW, KSCreenH - 19 -64) style:UITableViewStylePlain];
    _tableView.backgroundColor = graySectionColor;
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:_tableView];
    
    
    CGFloat labH = 30;
    CGFloat startX = [UIView getWidth:10];
    CGFloat laby = 10;
    CGFloat labW = [UIView getWidth:60];
    CGFloat tfX = labW + startX +20;
    CGFloat tfW = KSCreenW - tfX - startX;
    CGFloat lineW = KSCreenW - startX;
    
    
    UIView *bgview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, 100)];
    bgview.backgroundColor = [UIColor whiteColor];
    [_tableView addSubview:bgview];
    
    UIView *lineView = [ViewTool getLineViewWith:CGRectMake(0, 0, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [bgview addSubview:lineView];
    
    UILabel *lab1 = [[UILabel alloc]initWithFrame:CGRectMake(startX, (2*ROWH -labH)/2, labW, labH)];
    lab1.text = _titleArray[0];
    [ViewTool setLableFont14:lab1];
    lab1.textColor = lightGrayFontColor;
    [bgview addSubview:lab1];
    
    UIImageView *rightImg = [[UIImageView alloc]initWithFrame:CGRectMake(KSCreenW - 40, (2*ROWH -40)/2, 40, 40)];
    rightImg.image = [UIImage imageNamed:@"HY_list_icon_arrow"];
    [bgview addSubview:rightImg];
    
    _headerImg = [[UIButton alloc]initWithFrame:CGRectMake(rightImg.x - 60 -5, (2*ROWH -60)/2, 60, 60)];
    NSString  *imageStr =[NSString stringWithFormat:@"%@%@",LoadImageUrl,_logo];
    [_headerImg sd_setBackgroundImageWithURL:[NSURL URLWithString:imageStr] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"HY_list_icon_head"]];
    [_headerImg addTarget:self action:@selector(clickToChangeHeaderImage) forControlEvents:UIControlEventTouchUpInside];
    _headerImg.layer.cornerRadius = 60/2;
    _headerImg.layer.masksToBounds = YES;
    [bgview addSubview:_headerImg];
    
    UIButton *headBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, 2*ROWH)];
    [headBtn addTarget:self action:@selector(clickToChangeHeaderImage) forControlEvents:UIControlEventTouchUpInside];
    headBtn.userInteractionEnabled = YES;
    [bgview addSubview:headBtn];
    
    
    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(startX, ROWH*2-1, lineW, 1) withBackgroudColor:grayLineColor];
    [bgview addSubview:line1];
    
    for (int i=1; i<_titleArray.count; i++) {
        
        UILabel *lab1 = [[UILabel alloc]initWithFrame:CGRectMake(startX, line1.maxY + laby + ROWH*(i-1), labW, labH)];
        lab1.text = _titleArray[i];
        lab1.textColor = lightGrayFontColor;
        [bgview addSubview:lab1];
        [ViewTool setLableFont14:lab1];
        
        UIView *line = [ViewTool getLineViewWith:CGRectMake(startX, line1.maxY + ROWH*i -1, lineW, 1) withBackgroudColor:grayLineColor];
        [bgview addSubview:line];
        
        if (i == _titleArray.count - 1) {
            line.frame = CGRectMake(0, line1.maxY + ROWH*i -1, KSCreenW, 1);
        }
    }
    
    _nameLab = [[UILabel alloc]initWithFrame:CGRectMake(tfX, line1.maxY + laby, tfW, labH)];
    _nameLab.text = _name;
    _nameLab.textColor = UIColorFromRGB(0x545361);
    [ViewTool setLableFont14:_nameLab];
    [bgview addSubview:_nameLab];
    
    _telLab = [[UILabel alloc]initWithFrame:CGRectMake(tfX, _nameLab.maxY + 2*laby, tfW, labH)];
    _telLab.text = _phone;
    _telLab.textColor = UIColorFromRGB(0x545361);
    [ViewTool setLableFont14:_telLab];
    [bgview addSubview:_telLab];
    
    UIImageView *rightImg1 = [[UIImageView alloc]initWithFrame:CGRectMake(KSCreenW - 40, _telLab.maxY + laby +( ROWH -40)/2, 40, 40)];
    rightImg1.image = [UIImage imageNamed:@"HY_list_icon_arrow"];
    [bgview addSubview:rightImg1];
    
    UIImageView *qrImg = [[UIImageView alloc]initWithFrame:CGRectMake(rightImg.x - 25 -5, _telLab.maxY + laby +( ROWH -25)/2, 25, 25)];
    qrImg.image = [UIImage imageNamed:@"HY_list_icon_QR"];
    [bgview addSubview:qrImg];
    
    UIButton *qrBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, _telLab.maxY + laby, KSCreenW, ROWH)];
    [qrBtn addTarget:self action:@selector(getQRCode) forControlEvents:UIControlEventTouchUpInside];
    qrBtn.userInteractionEnabled = YES;
    [bgview addSubview:qrBtn];
    
    _departTF = [[UITextField alloc]initWithFrame:CGRectMake(tfX, qrImg.maxY + 2*laby, tfW, labH)];
    _departTF.textColor = UIColorFromRGB(0x545361);
    _departTF.text = _department;
    _departTF.font = [ViewTool getFont14];
    _departTF.delegate = self;
    _departTF.userInteractionEnabled = NO;
    [bgview addSubview:_departTF];
    
    _positionTF = [[UITextField alloc]initWithFrame:CGRectMake(tfX, _departTF.maxY + 2*laby, tfW, labH)];
    _positionTF.textColor = UIColorFromRGB(0x545361);
    _positionTF.text = _position;
    _positionTF.font = [ViewTool getFont14];
    _positionTF.delegate = self;
    _positionTF.userInteractionEnabled  = NO;
    [bgview addSubview:_positionTF];
    
    bgview.frame = CGRectMake(0, 0, KSCreenW, 7*ROWH);
    _tableView.contentSize = CGSizeMake(KSCreenW, bgview.maxY);
    
}
- (void)createQRView{
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    
    _qrView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, KSCreenH)];
    _qrView.backgroundColor = [UIColor blackColor];
    _qrView.alpha = 0.5;
    _qrView.hidden = YES;
    [window addSubview:_qrView];
    
    _bgImage = [[UIImageView alloc]initWithFrame:CGRectMake([UIView getWidth:60], [UIView getHeight:120], KSCreenW - 2*[UIView getWidth:60], KSCreenW - 2*[UIView getWidth:60])];
    _bgImage.backgroundColor = [UIColor whiteColor];
    _bgImage.hidden = YES;
    _bgImage.layer.cornerRadius = 5;
    _bgImage.layer.masksToBounds = YES;
    [window addSubview:_bgImage];
    
    QRbutton = [[UIButton alloc]initWithFrame:CGRectMake((KSCreenW -40) / 2, _bgImage.maxY + 50, 40, 40)];
    [QRbutton setImage:[UIImage imageNamed:@"HY_btn_close"] forState:UIControlStateNormal];
    [QRbutton addTarget:self action:@selector(hiddenQRView) forControlEvents:UIControlEventTouchUpInside];
    QRbutton.hidden = YES;
    [window addSubview:QRbutton];
    
    qrNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, [UIView getHeight:20], KSCreenW - 2*[UIView getWidth:40], [UIView getHeight:30])];
    qrNameLabel.textColor = [UIColor whiteColor];
    qrNameLabel.textAlignment = NSTextAlignmentCenter;
    [_bgImage addSubview:qrNameLabel];
    
    _qrImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _bgImage.width, _bgImage.height)];
    NSString  *qrImageStr =[NSString stringWithFormat:@"%@%@",LoadImageUrl,_imag];
    _qrImageView.image = [QRCodeGenerator qrImageForString:qrImageStr imageSize:300];
    [_bgImage addSubview:_qrImageView];
    
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toHiddenQRView:)];
    [_qrView addGestureRecognizer:tapGesture];
    
}
- (void)getRightNavigationBar{
    btnSave = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 20)];
    [btnSave setTitle:@"保存" forState:UIControlStateNormal];
    [btnSave setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btnSave.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [btnSave addTarget:self action:@selector(saveClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btnSave];
    btnSave.hidden = YES;
    self.navigationItem.rightBarButtonItem = item;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
//    btnSave.hidden = NO;
}
- (void)saveClick:(UIButton *)btn{
    NSDictionary * dic =@{@"token":TOKEN,@"uid":@(UID),@"did":@(_departID),@"position":@(_positionID),@"id":@(_uID)};
    NSLog(@"修改部门的参数%@",dic);
    [DataTool postWithUrl:DEPARTMENT_UPDATE_USER_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@+++++--",jsonDic);
        if ([jsonDic[@"code"]integerValue] == 100 ) {
            [SVProgressHUD showSuccessWithStatus:@"修改成功"];
            [self performSelector:@selector(goToBack) withObject:nil afterDelay:1];
        }else{
            [DataTool showMessage:jsonDic[@"message"] view:self];
        }
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}
- (void)getQRCode{
    
    [UIView animateWithDuration:0.25 animations:^{
        _qrView.hidden = NO;
        _bgImage.hidden = NO;
        QRbutton.hidden = NO;
    }];
}
- (void)hiddenQRView{
    [UIView animateWithDuration:0.25 animations:^{
        _qrView.hidden = YES;
        _bgImage.hidden = YES;
        QRbutton.hidden = YES;
    }];
}
- (void)toHiddenQRView:(UITapGestureRecognizer *)tap{
    [UIView animateWithDuration:0.25 animations:^{
        _qrView.hidden = YES;
        _bgImage.hidden = YES;
        QRbutton.hidden = YES;
    }];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [UIView animateWithDuration:0.25 animations:^{
        _qrView.hidden = YES;
        _bgImage.hidden = YES;
    }];
}

- (void)goToBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.hidesBottomBarWhenPushed = NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
}

- (void)initData{
    
    NSDictionary * dic =@{@"token":TOKEN,@"uid":@(UID)};
    [DataTool postWithUrl:MY_HOMEPAGE_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@+++++--wodexiangqing",jsonDic);
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}
#pragma mark
#pragma mark------修改头像
- (void)clickToChangeHeaderImage{
    if(IOS7){
        UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",@"打开相机", nil];
        [actionSheet showInView:self.view];
    }else{
        UIAlertController * alertionControll = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self takePhotoFromLibrary];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"打开相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self takePhotoFromCamera];
        }];
        UIAlertAction * action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertionControll addAction:action1];
        [alertionControll addAction:action2];
        [alertionControll addAction:action3];
        if(alertionControll != nil){
            [self presentViewController:alertionControll animated:YES completion:nil];
        }
    }
    
}
#pragma mark
#pragma mark --actionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self takePhotoFromLibrary];
    }else if (buttonIndex == 1){
        [self takePhotoFromCamera];
    }
}
- (void)takePhotoFromLibrary{
    UIImagePickerController *imagePick = [[UIImagePickerController alloc] init];
    imagePick.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePick.delegate = self;
    imagePick.allowsEditing = YES;
    [self presentViewController:imagePick animated:YES completion:nil];
}
- (void)takePhotoFromCamera{
    
    UIImagePickerController *imagePic = [[UIImagePickerController alloc]init];
    imagePic.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePic.delegate = self;
    imagePic.allowsEditing = YES;
    [self presentViewController:imagePic animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    
    [_headerImg setImage:image forState:UIControlStateNormal];
    
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    NSString *str = [imageData base64Encoding];
    
    NSDictionary * dic =@{@"token":TOKEN,@"uid":@(UID),@"logo":str};
    [DataTool postWithUrl:UPDATE_USER_LOGO_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@+++++--",jsonDic);
        [[NSUserDefaults standardUserDefaults] setObject:jsonDic[@"logourl"] forKey:@"logo"];
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}

- (void)actionSheetCancel:(UIActionSheet *)actionSheet
{
    [actionSheet dismissWithClickedButtonIndex:2 animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
